package reflective;

import org.junit.Test;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

public class ReflectiveTest7 {
    public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        // 反射实例化
//        new User();
//        new User("ccc",24);

        // newInstance创建
        Class<?> clazz = Class.forName("reflective.User");
        Object o = clazz.newInstance();
        System.out.println(o);


        // 获取有参构造创建
        Constructor<?> constructor = clazz.getDeclaredConstructor(String.class, int.class);
        Object ccc = constructor.newInstance("ccc", 24);
        System.out.println(ccc);

    }

    @Test
    public void test1() throws ClassNotFoundException, NoSuchFieldException, InstantiationException, IllegalAccessException {
        // 设置属性
        Class<?> clazz = Class.forName("reflective.User");
        Field field = clazz.getDeclaredField("age");
        field.setAccessible(true);

        Object user = clazz.newInstance();
        field.set(user, 24);

        System.out.println(field.get(user));

        System.out.println(user);

    }

    @Test
    public void test2() throws ClassNotFoundException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException {
        // 执行方法
        Class<?> clazz = Class.forName("reflective.User");
        Method setName = clazz.getDeclaredMethod("setName", String.class);
        User o = (User) clazz.newInstance();
        setName.invoke(o, "ccc");
        System.out.println(o);  // User{name='ccc', age=0}
    }

}

class User {
    private String name;
    private int age;

    public User() {
    }

    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "User{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}
